package com.example.common;

import com.example.common.exception.*;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 创建错误响应
     *
     * @param errorCode 错误码
     * @param status HTTP状态码
     * @return 错误响应实体
     */
    private static ResponseEntity<ResultResponse<?>> errorResponseEntity(ErrorCode errorCode, HttpStatus status) {
        return new ResponseEntity<>(ResultResponse.failure(errorCode), status);
    }

    /**
     * 处理非法参数异常
     *
     * @param ex 非法参数异常
     * @return 错误响应
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ResultResponse<?>> handleIllegalArgumentException(IllegalArgumentException ex) {
        return errorResponseEntity(ErrorCode.PARAM_INVALID, HttpStatus.BAD_REQUEST);
    }
    
    /**
     * 处理参数校验异常
     *
     * @param ex 参数校验异常
     * @return 错误响应
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ResultResponse<?>> handleValidationException(MethodArgumentNotValidException ex) {
        // 获取所有验证错误信息
        String errorMessage = ex.getBindingResult().getFieldErrors().stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining(", "));
        
        ResultResponse<?> response = ResultResponse.failure(ErrorCode.PARAM_INVALID)
                .addMetadata("validationErrors", errorMessage);
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
    
    /**
     * 处理资源未找到异常
     *
     * @param ex 资源未找到异常
     * @return 错误响应
     */
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ResultResponse<?>> handleResourceNotFoundException(ResourceNotFoundException ex) {
        return errorResponseEntity(ErrorCode.RESOURCE_NOT_FOUND, HttpStatus.NOT_FOUND);
    }
    
    /**
     * 处理资源冲突异常
     *
     * @param ex 资源冲突异常
     * @return 错误响应
     */
    @ExceptionHandler(ResourceConflictException.class)
    public ResponseEntity<ResultResponse<?>> handleResourceConflictException(ResourceConflictException ex) {
        ResultResponse<?> response = ResultResponse.failure(ErrorCode.BUSINESS_ERROR)
                .addMetadata("conflictData", ex.getConflictData());
        return new ResponseEntity<>(response, HttpStatus.CONFLICT);
    }
    
    /**
     * 处理文件上传大小超限异常
     *
     * @param ex 文件上传大小超限异常
     * @return 错误响应
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<ResultResponse<?>> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex) {
        return errorResponseEntity(ErrorCode.PARAM_INVALID, HttpStatus.PAYLOAD_TOO_LARGE);
    }
    
    /**
     * 处理未授权异常
     *
     * @param ex 未授权异常
     * @return 错误响应
     */
    @ExceptionHandler(UnauthorizedException.class)
    public ResponseEntity<ResultResponse<?>> handleUnauthorizedException(UnauthorizedException ex) {
        return errorResponseEntity(ErrorCode.UNAUTHORIZED, HttpStatus.UNAUTHORIZED);
    }
    
    /**
     * 处理无权限异常
     *
     * @param ex 无权限异常
     * @return 错误响应
     */
    @ExceptionHandler(ForbiddenException.class)
    public ResponseEntity<ResultResponse<?>> handleForbiddenException(ForbiddenException ex) {
        return errorResponseEntity(ErrorCode.FORBIDDEN, HttpStatus.FORBIDDEN);
    }
    
    /**
     * 处理未支持的媒体类型异常
     *
     * @param ex 未支持的媒体类型异常
     * @return 错误响应
     */
    @ExceptionHandler(UnsupportedMediaTypeException.class)
    public ResponseEntity<ResultResponse<?>> handleUnsupportedMediaTypeException(UnsupportedMediaTypeException ex) {
        return errorResponseEntity(ErrorCode.PARAM_INVALID, HttpStatus.UNSUPPORTED_MEDIA_TYPE);
    }
    
    /**
     * 处理业务异常
     *
     * @param ex 业务异常
     * @return 错误响应
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ResultResponse<?>> handleBusinessException(BusinessException ex) {
        return new ResponseEntity<>(ResultResponse.failure(ex.getErrorCode()), HttpStatus.INTERNAL_SERVER_ERROR);
    }
    
    /**
     * 处理通用异常
     *
     * @param ex 异常
     * @return 错误响应
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResultResponse<?>> handleGenericException(Exception ex) {
        return errorResponseEntity(ErrorCode.SYSTEM_ERROR, HttpStatus.INTERNAL_SERVER_ERROR);
    }
} 